#include "filedownloadprovider.h"

#include "curlwrapper/chttpclient.h"
#include "threadWrapper/processhelper.h"


#define LOG_TAG "filedownloadprovider"
#include "publicfun/debug.h"

#if CURLDOWNLOAD
static void downloadcallback(CURL *curl)
{
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10*60);
}

#endif

int downloadToPath(const char *url, const char *destpath)
{
    LOGD("%s E", __func__);
    int ret = 0;
    if(makesureDir(destpath)){
        LOGE("%s:dir failed", __func__);
        return -1;
    }

#if CURLDOWNLOAD
    int trytime = 2;
    CHttpClient curl;
    vector<string> headers;
    headers.push_back("User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.45.134 Safari/537.36 QBCore/3.43.45.400 QQBrowser/9.0.2524.400");

    curl.setAutoDecoding("gzip, deflate");

    if(access(destpath, F_OK)){
        string tmp = string(destpath) + ".tmp";
        FILE *fp = fopen(tmp.c_str(), "wb");
        if(fp){
            do{
                LOGD("%s:try%s:%d", __func__, destpath, trytime);
                fseek(fp, 0, SEEK_SET);
                ret = curl.Gets(url, fp, NULL, downloadcallback, headers);
                if(ret){
                    LOGE("%s download failed", __func__);
                    sleep(1);
                }else{
                    break;
                }
            }while(trytime-- > 0);

            fclose(fp);

            if(ret){
                unlink(tmp.c_str());
            }else{
                ret = rename(tmp.c_str(), destpath);
            }

        }else{
            LOGE("%s open[%s]failed %s", __func__, destpath, strerror(errno));
            ret = -1;
        }
    }else{
        LOGI("%s:skip download %s", __func__, destpath);
    }
#else
    char *cmd = NULL;
    while (true) {
        if(access("/sdzw/ini/wesingdownload.conf", F_OK) == 0){
            asprintf(&cmd, "aria2c -c --conf-path=/sdzw/ini/wesingdownload.conf  \"%s\" -o %s", url, destpath);
        }else{
            asprintf(&cmd, "aria2c -c \"%s\" -o %s", url, destpath);
        }
        ret = mysystem(cmd);
        free(cmd);
        if (ret == 0) {
            break;
        } else if (ret == 1) {
            LOGI("%s:[%s]Unrecognized URI or unsupported protocol", __func__, url);
            break;
        } else if (ret == 3) {
            LOGI("%s:[%s]Resource not found", __func__, url);
            break;
        } else if (ret == 19) {
            LOGI("%s:[%s]Domain name not found", __func__, url);
            break;
        } else if (ret == 22) {
            LOGI("%s:[%s]The response status is not successful. status=400/405", __func__, url);
            break;
        } else if (ret == E2BIG) {
            LOGI("%s:[%s]The argument list is too big.", __func__, url);
            break;
        } else {
            LOGI("%s:[%s]unknown error:%d", __func__, url, ret);
        }
        sleep(1);
    }
#endif
    return ret;
}
